__author__ = "Chengye zhao (chengyezhao@gmail.com)"

from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from product import Product, getProductListXml
import logging

class MainJob(webapp.RequestHandler):
	def get(self):
		sort_by = self.request.get("sort")
		if not sort_by:
			sort_by = 'startTime'
		sort_order = self.request.get("order")
		if not sort_order:
			sort_order = 'DESC'
		page = self.request.get("page")
		if not page:
			page = '1'
		if int(page) < 1:
			page = '1'
		size = self.request.get("size")
		if not size:
			size = '20'
		if int(size) < 1:
			size = '20'

		url = self.request.get("url")
		category = self.request.get("category")
		site_lists = self.request.get("site")

		offset = (int(page) - 1) * int(size)
		queryStr = "SELECT * from Product"

		first_where = True
		if site_lists is not None and site_lists != '':
			queryStr += " WHERE site in ('" + site_lists.replace("_", "','") + "') "
			first_where = False

		if url is not None and url != '':
			if first_where:
				queryStr += " WHERE url = '" + url + "'"
			else:
				queryStr += " AND url = '" + url + "'"
		elif category is not None and category != '':
			if first_where:
				queryStr += " WHERE category = " + str(category)
			else:
				queryStr += " AND category = " + str(category)

		if sort_by and sort_order:
			queryStr += " ORDER BY " + sort_by + " " + sort_order

		queryStr += " LIMIT " + size + " OFFSET " + str(offset)
		#logging.info(queryStr)

		#result = memcache.get(queryStr)
		result = None
		if result is not None:
			self.response.out.write(result)
		else:

			q = db.GqlQuery(queryStr)
			doc_str = getProductListXml(q)
			#if not memcache.add(queryStr, doc_str, 600):
			#	pass
			self.response.out.write(doc_str)

application = webapp.WSGIApplication(
	[('/list', MainJob)],
	debug=False)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
